package cn.cellcom.agent.online.iq.visitor;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.online.client.Client;
import cn.cellcom.agent.online.client.VisitorClient;
import cn.cellcom.agent.online.iq.AbstractChainedProcessor;
import cn.cellcom.agent.online.iq.Processor;
import cn.cellcom.agent.online.iq.ProcessorResult;
import cn.cellcom.agent.online.message.MessageConstant;
import cn.cellcom.agent.online.message.MessageReceipt;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.pojo.TGroup;
import cn.cellcom.agent.struts.form.VisitorForm;
import cn.cellcom.jar.biz.AbstractBiz;

public class VisitorActionProcessor extends AbstractChainedProcessor {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	public VisitorActionProcessor(Processor next) {
		super(next);
	}

	@Override
	public ProcessorResult doProcess(Map<String, AbstractBiz> bizs, Client client, VisitorForm cf) {
		VisitorClient ac = (VisitorClient) client;
		SessionWrapper session = ac.getSessionByPid(cf.getPid());
		if (session != null) {
			TGroup g = null;
			if (session.getGroup() != null) {
				g = session.getGroup().getGroup();
			}
			ac.archiveWithId(session, cf.getId(), cf.getEvent(), cf.getValue(), cf.getMultiType(), g);
		} else {
			log.error("[{}] no session exist for archive for pid[{}]", ac.getId(), cf.getPid());
			//ac.sendBizMessage(new ErrorMessage(ac.getId()));
			return new ProcessorResult(false, this, null);
		}
		String sid = session.getId();
		if (MessageConstant.MESSAGE_EVENT.CHAT.name().equals(cf.getEvent())) {
			session.message(ac, cf.getValue(), cf.getValue2(), cf.getMultiType());
		} else if (MessageConstant.MESSAGE_EVENT.END_SESSION.name().equals(cf.getEvent())) {
			log.info("[{}] end the session[{}]", ac.getId(), sid);
			ac.endSession(sid, AgentConstant.SESSION_END_TYPE.BY_VISITOR);
		} else if (MessageConstant.MESSAGE_EVENT.CANCEL_QUEUE.name().equals(cf.getEvent())) {
			log.info("[{}] cancel queue in the session[{}]", ac.getId(), sid);
			ac.cancelQueue(sid, AgentConstant.SESSION_END_TYPE.BY_VISITOR);
		}
		return new ProcessorResult(true, this, new MessageReceipt(cf.getId(), true));
	}

	@Override
	public boolean isAcceptable(VisitorForm cf) {
		boolean b = MessageConstant.MESSAGE_EVENT.END_SESSION.name().equals(cf.getEvent())
				|| MessageConstant.MESSAGE_EVENT.CANCEL_QUEUE.name().equals(cf.getEvent())
				|| MessageConstant.MESSAGE_EVENT.CHAT.name().equals(cf.getEvent());
		return b;
	}
}
